package com.example.xyxwebbackend001.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.xyxwebbackend001.mapper.*;
import com.example.xyxwebbackend001.model.DTO.RecPublishDTO;
import com.example.xyxwebbackend001.model.DTO.PostStatisticsDTO;
import com.example.xyxwebbackend001.model.entity.*;
import com.example.xyxwebbackend001.model.enums.TagEnum;
import com.example.xyxwebbackend001.model.vo.FoodListVO;
import com.example.xyxwebbackend001.model.vo.TouristListVO;
import com.example.xyxwebbackend001.model.vo.TradCraftListVO;
import com.example.xyxwebbackend001.service.ManaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

@Service
public class ManaServiceImpl implements ManaService {

    @Autowired
    private TPostsxMapper tPostsxMapper;

    @Autowired
    private FoodMapper foodMapper;

    @Autowired
    private FoodContentMapper foodContentMapper;

    @Autowired
    private TradCraftMapper tradCraftMapper;

    @Autowired
    private TradCraftContentMapper tradCraftContentMapper;

    @Autowired
    private TouristMapper touristMapper;

    @Autowired
    private TouristContentMapper touristContentMapper;

    @Override
    public Map<String, Object> getTPostStatistics() {
        LocalDateTime now = LocalDateTime.now();

        // 近7天数据
        List<PostStatisticsDTO> last7Days = tPostsxMapper.selectRecentPostCounts(now.minusDays(7));
        // 近30天数据
        List<PostStatisticsDTO> last30Days = tPostsxMapper.selectRecentPostCounts(now.minusDays(30));

        return Map.of(
                "last7Days", last7Days,
                "last30Days", last30Days
        );
    }

    @Override
    public List<Map<String, Object>> getTagStatistics() {
        StringJoiner enumSql = new StringJoiner(" UNION ALL ");
        for (TagEnum tag : TagEnum.values()) {
            enumSql.add(String.format("SELECT %d AS code, '%s' AS name",
                    tag.getCode(), tag.getName()));
        }
        return tPostsxMapper.selectTagStatistics(enumSql.toString());
    }

    @Override
    public List<Map<String, Object>> getCityStatistics() {
        List<Map<String, Object>> stats = tPostsxMapper.selectCityStats();
        return stats;
    }

    @Override
    @Transactional
    public Integer createFoodRec(RecPublishDTO dto) {
        Food food = new Food();
        food.setTitle(dto.getTitle());
        food.setCityId(dto.getCityId());
        food.setCoverPath(dto.getCover().getCoverPath());
        foodMapper.insert(food);

        // 获取自增ID
        Integer foodId = food.getFoodId();

        List<FoodContent> contents = dto.getContent().stream().map(contentDTO -> {
            FoodContent content = new FoodContent();
            content.setFoodId(foodId);
            content.setType(contentDTO.getType());
            content.setContent(contentDTO.getContent());

            content.setListItems(StringUtils.hasText(contentDTO.getListItems()) ?
                    contentDTO.getListItems() : null);
            content.setFilePath(StringUtils.hasText(contentDTO.getFilePath()) ?
                    contentDTO.getFilePath() : null);

            return content;
        }).collect(Collectors.toList());

       if (!contents.isEmpty()) {
           foodContentMapper.batchInsert(contents);
       }

        return foodId;
    }

    @Override
    @Transactional
    public Integer createCraftRec(RecPublishDTO dto) {
        TradCraft craft = new TradCraft();
        craft.setTitle(dto.getTitle());
        craft.setCityId(dto.getCityId());
        craft.setCoverPath(dto.getCover().getCoverPath());
        tradCraftMapper.insert(craft);

        // 获取自增ID
        Integer trId = craft.getTrId();

        // 2. 保存内容块到food_content表
        List<TradCraftContent> contents = dto.getContent().stream().map(contentDTO -> {
            TradCraftContent content = new TradCraftContent();
            content.setTrId(trId);
            content.setType(contentDTO.getType());
            content.setContent(contentDTO.getContent());

            content.setListItems(StringUtils.hasText(contentDTO.getListItems()) ?
                    contentDTO.getListItems() : null);
            content.setFilePath(StringUtils.hasText(contentDTO.getFilePath()) ?
                    contentDTO.getFilePath() : null);

            return content;
        }).collect(Collectors.toList());

        if (!contents.isEmpty()) {
            tradCraftContentMapper.batchCraftInsert(contents);
        }

        return trId;
    }

    @Override
    @Transactional
    public Integer createTouristRec(RecPublishDTO dto) {
        Tourist tourist = new Tourist();
        tourist.setTitle(dto.getTitle());
        tourist.setCityId(dto.getCityId());
        tourist.setCoverPath(dto.getCover().getCoverPath());
        touristMapper.insert(tourist);

        // 获取自增ID
        Integer toId = tourist.getToId();

        // 2. 保存内容块到food_content表
        List<TouristContent> contents = dto.getContent().stream().map(contentDTO -> {
            TouristContent content = new TouristContent();
            content.setToId(toId);
            content.setType(contentDTO.getType());
            content.setContent(contentDTO.getContent());

            content.setListItems(StringUtils.hasText(contentDTO.getListItems()) ?
                    contentDTO.getListItems() : null);
            content.setFilePath(StringUtils.hasText(contentDTO.getFilePath()) ?
                    contentDTO.getFilePath() : null);

            return content;
        }).collect(Collectors.toList());

        if (!contents.isEmpty()) {
            touristContentMapper.batchTouristInsert(contents);
        }

        return toId;
    }

    @Override
    public List<FoodListVO> getFoodList(String keyword) {
        return foodMapper.getFoodList(keyword);
    }
    public void updateFoodStatus(Integer id, Integer status) {
        UpdateWrapper<Food> wrapper = new UpdateWrapper<>();
        wrapper.set("status", status)
                .eq("food_id", id);
        foodMapper.update(null, wrapper);
    }

    @Override
    public List<TradCraftListVO> getTradCraftList(String keyword) {
        return tradCraftMapper.getCraftList(keyword);
    }

    @Override
    public void updateTradCraftStatus(Integer id, Integer status) {
        UpdateWrapper<TradCraft> wrapper = new UpdateWrapper<>();
        wrapper.set("status", status)
                .eq("tr_id", id);
        tradCraftMapper.update(null, wrapper);
    }

    @Override
    public List<TouristListVO> getTouristList(String keyword) {
        return touristMapper.getTouristList(keyword);
    }

    @Override
    public void updateTouristStatus(Integer id, Integer status) {
        UpdateWrapper<Tourist> wrapper = new UpdateWrapper<>();
        wrapper.set("status", status)
                .eq("to_id", id);
        touristMapper.update(null, wrapper);
    }
}
